<?php
/**
 * 分页类
 */
namespace yphp;

class Page extends Instance
{
    # 分页对象
    protected $obj;

    # 初始数据
    protected $data;

    # 限制数量
    protected $num;

    # 计算总数
    protected $count;

    function construct($obj,$num = null)
    {
        if(!($obj instanceof DbBase)) throw new \Exception('分页对象必须继承于DbBase');
        $this->obj = $obj;
        $this->data = $obj->dataSql();
        $this->num = is_null($num) ? Config::web('pagelimit') : $num;
    }

    // 获取分页数据
    function pageData($rArr = false)
    {
        $page = $this->pageCount()['page'];
        if (!$page) return [];
        $this->obj->makeData($this->data)->limit(($page - 1)*$this->num,$this->num);
        $rm = new \ReflectionMethod($this->obj, 'select');

        return $rm->invokeArgs($this->obj, [$rArr]);
    }

    // 计算总数，总页码
    function pageCount()
    {
        if (is_null($this->count)){
            $count = $this->obj->makeData($this->data)->limit(0, 1)->one('count(*)') ?: 0;
            $pageNum = ceil($count/$this->num);

            $page = (int)Request::instance()->param(Config::web('page'),1);
            if($page < 1 || $page > $pageNum || $count === 0) $page = false;

            $this->count = ['count'=>$count,'pagenum'=>$pageNum,'page'=>$page];
        }
        return $this->count;
    }

    // 生成页码
    function createPage()
    {
        # 数据总数
        $count = $this->pageCount()['count'];
        # 总页码
        $pagenum = $this->pageCount()['pagenum'];
        # 当前页码
        $page = $this->pageCount()['page'];

        if (!$page) return '';
        $query = '';
        foreach (Request::instance()->get() as $k => $v) {
            if ($k === Config::web('page')) continue;
            $query .= $k . '=' . $v . '&';
        }

        $url = Request::instance()->path() . '?' . $query . Config::web('page') . '=';

        # 页码字符串
        $str = '';
        # 首页
        $str .= "<a href='".$url.'1'."'>首页</a>";

        # 上一页
        if ($page - 1 > 0) {
            $str .= "<a href='".$url.($page - 1)."'>上一页</a>";
        }

        # 中间区块
        if($pagenum > 1){
            for ($i=1; $i < $pagenum; $i++) {
                if ($page - 5 > $i || $page + 5 < $i) continue;
                if(key_exists(Config::web('page'),Request::instance()->get()) && $page === $i){
                    $str .= "<a class='current' href='".$url.($i)."'>".$i."</a>";
                } else {
                    $str .= "<a href='".$url.($i)."'>".$i."</a>";
                }
            }
        }

        # 下一页
        if ($page + 1 <= $pagenum) {
            $str .= "<a href='".$url.($page + 1)."'>下一页</a>";
        }

        # 尾页
        $str .= "<a href='".$url.$pagenum."'>尾页</a>";

        return '<div class="pagination">'.$str.'</div>';
    }
}